package itsm.isperp.module.controller.app;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.utils.TreeNodeUtils;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.app.VAppDepartmentUser;
import itsm.isperp.module.dto.app.VAppRoleMenu;
import itsm.isperp.module.entity.app.AppMenu;
import itsm.isperp.module.entity.app.AppRole;
import itsm.isperp.module.service.app.AppMenuService;
import itsm.isperp.module.service.app.AppRoleService;
import itsm.isperp.module.service.knowledge.KngKnowledgeCategoryService;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 系统角色控制器
 * 
 * 
 * @author lizx
 * @date 2013-2-16
 * @version V1.0
 */
@Controller
@RequestMapping("app/role")
public class AppRoleController extends BaseController<AppRole> {

	/**
	 * 系统角色管理服务
	 */
	@Autowired
	protected AppRoleService appRoleService;

	@Autowired
	protected AppMenuService appMenuService;

	@Override
	public AppRoleService getService() {
		return this.appRoleService;
	}

	@Override
	public String getPageTitle() {
		return "角色";
	}

	@RequestMapping("edit")
	public ModelAndView edit(String id, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = this.getModelAndView();
		AppRole model = this.getService().findOne(id);
		if (model == null) {
			model = new AppRole();
			model.setId(HibernateUUIDGenerator.generate());
			model.setStatus(true);
		}
		mv.addObject("model", model);
		mv.addObject("pageTitle", this.getPageTitle());
		return mv;
	}

	@RequestMapping("/getMenus")
	@ResponseBody
	public List<? extends ITreeNode> getMenus(String roleId) {

		List<AppMenu> menus = appMenuService.findAll(
				new JqGridRequest().isPageable(false).setSort("order_num",
						Direction.ASC)).getContent();

		List<VAppRoleMenu> rolemenus = this.appRoleService
				.findResourceRolesByRole(roleId);

		Set<String> set = new HashSet<String>();
		for (VAppRoleMenu r : rolemenus)
			set.add(r.getId());

		for (AppMenu menu : menus) {
			menu.setUrl(null);
			menu.setOpen(true);
			if (set.contains(menu.getId())) {
				menu.setChecked(true);
			}
		}

		return TreeNodeUtils.parseFormList(menus);
	}

	@RequestMapping("save")
	@ResponseBody
	@Override
	public ResultMessage save(AppRole model, HttpServletRequest req) {

		String permissionValue = req.getParameter("menuPermissionValue");

		String[] ps = null;
		if (StringUtils.isNotEmpty(permissionValue)) {
			ps = permissionValue.split(",");

		}

		this.getService().saveOrUpdate(model, ps);
		return ResultMessage.newInstance(true);
	}

	@RequestMapping("saveRoleUser")
	@ResponseBody
	public ResultMessage saveRoleUser(String roleId, String userName) {
		if(userName.indexOf(",")>-1)
		{
			 String[] names=userName.split(",");
			 for(String n:names)
			 {
				 this.appRoleService.saveRoleUser(roleId,
							n);
			 }
		}else
		{
			 this.appRoleService.saveRoleUser(roleId,
					userName);
		}
		return ResultMessage.newInstance(true);
	}

	@RequestMapping("listRoleUser")
	@ResponseBody
	public PageResponse<VAppDepartmentUser> listRoleUser(JqGridRequest request,
			HttpServletRequest req) {

		String roleId = req.getParameter("roleId");

		return this.appRoleService.getRoleUsers(roleId, request);
	}

	@RequestMapping("roleUserEdit")
	public ModelAndView roleUserEdit(String roleId) {
		ModelAndView mv = new ModelAndView("app/role/roleUserEdit");
		mv.addObject("roleId", roleId);

		AppRole role = this.getService().findOne(roleId);
		mv.addObject("roleName", role.getName());

		return mv;

	}

	@RequestMapping("deleteRoleUser")
	@ResponseBody
	public ResultMessage deleteRoleUser(String roleId, String id) {
		return this.appRoleService.deleteRoleUser(roleId, id);

	}

	@RequestMapping("roleResouceEdit")
	public ModelAndView roleResouceEdit(String rs, String roleId,
			HttpServletRequest re) {
		ModelAndView mv = this.getModelAndView();

		mv.addObject("model", this.getService().findOne(roleId));
		mv.addObject("rs", rs);

		return mv;
	}

	@RequestMapping("saveRoleResouce")
	@ResponseBody
	public ResultMessage saveRoleResouce(String id, String resourceValue,
			HttpServletRequest req) {

		String rs = req.getParameter("rs");

		String roleResouceTable = "app_role_"
				+ itsm.isperp.framework.utils.StringUtils.underscore(rs);

		String[] ps = null;
		if (StringUtils.isNotEmpty(resourceValue)) {
			ps = resourceValue.split(",");
		}
		this.getService().saveRoleResouce(id, roleResouceTable, ps);
		return ResultMessage.newInstance(true);
	}

	@RequestMapping("getResourceKngCategory")
	@ResponseBody
	public List<? extends ITreeNode> getResourceKngCategory(String roleId) {

		KngKnowledgeCategoryService kngKnowledgeCategoryService = ContextHolder
				.getSpringBean("kngKnowledgeCategoryService");

		List<? extends ITreeNode> menus = kngKnowledgeCategoryService.findAll();
		return getResource(roleId, menus, "app_role_kng_category",
				"kng_knowledge_category");
	}

	private List<? extends ITreeNode> getResource(String roleId,
			List<? extends ITreeNode> menus, String rs, String rsFrom) {
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		List<String> rolemenus = jdbcTemplate.queryForList("SELECT b.id FROM  "
				+ rs + " a INNER JOIN   " + rsFrom + "  b"
				+ " ON a.category_id=b.id " + " WHERE a.app_role_id='" + roleId
				+ "' ORDER BY b.order_num", String.class);

		Set<String> set = new HashSet<String>();
		for (String r : rolemenus) {
			set.add(r);
		}

		for (ITreeNode menu : menus) {
			menu.setOpen(true);
			if (set.contains(menu.getId())) {
				menu.setChecked(true);
			}
		}

		return TreeNodeUtils.parseFormList(menus);
	}
}
